/**
 * Created by Delicate on 2018/1/3.
 */
import React from 'react';
import {
    StyleSheet,
    View,
    Image,
    Text,
    ScrollView,
    TextInput,
    Keyboard,
    Animated,
    TouchableOpacity,
    DeviceEventEmitter
} from 'react-native';

import NavBar from '../../components/NavBarView'
import HorizontalMenu from '../../components/HorizontalMenuView'
import DemandService from '../../services/Demand'
import Constants from '../../config/Constants'
import {DemandState} from '../../config/dict/DemandState'


let _self;

class Views extends React.Component {

    constructor(props) {
        super(props);
        _self = this;
        this.state = {
            demand: {},
            list: [],
            pageNumber: 1,
            pageSize: 10,
            keyHeight: new Animated.Value(0),
            id: '',
            sendMessage: ''
        };
        this.state.id = this.props.navigation.state.params.id;
    }

    componentWillMount() {
        this.keyboardDidShowListener = Keyboard.addListener('keyboardWillShow', (e) => this.keyBoardShow(e));
        this.keyboardDidHideListener = Keyboard.addListener('keyboardWillHide', (e) => this.keyBoardHide(e));
    }

    componentDidMount() {
        this.load(1);
    }

    componentWillUnmount() {
        this.keyboardDidShowListener.remove();
        this.keyboardDidHideListener.remove();
    }

    keyBoardShow(e) {
        Animated.timing(_self.state.keyHeight, {
            toValue: e.endCoordinates.height,
            duration: 210
        }).start();
    }

    keyBoardHide(e) {
        _self.state.keyHeight.setValue(0);
    }

    toEnd() {
        setTimeout(() => {
            _self.refs.scrollView.scrollToEnd({animated: false});
        }, 100);
    }

    async load(pageNumber) {
        const {result, message, data} = await DemandService.messages({
            params: {
                pageNumber,
                requireId: _self.state.id,
                pageSize: _self.state.pageSize
            }
        });
        if (result) {
            _self.setState({
                list: data.list,
                demand: data.requirement
            })
        } else {
            Toast.show(message)
        }
    }

    //input改变触发
    inputChange(sendMessage) {
        _self.setState({sendMessage});
    }

    async submit() {
        const {result, message} = await DemandService.sendMessage({
            params: {
                requireId: _self.state.id,
                message: _self.state.sendMessage
            }
        });
        DeviceEventEmitter.emit(Constants.LISTENER_MESSAGES);
        if (result) {
            let list = _self.state.list;
            list.push({
                chat_receive_name: "",
                chat_send_name: "",
                create_date: '刚刚',
                fk_asset_requirement: "",
                fk_user_info_id: "",
                id: "",
                message_content: _self.state.sendMessage,
                update_date: null,
                user_type: "02"
            })
            _self.setState({
                list,
                sendMessage: ''
            })
        } else {
            Toast.show(message)
        }
    }

    render() {
        return (
            <View style={base.baseOuter}>
                <NavBar host={this} title={this.state.title || '需求沟通'}/>
                <View style={styles.demandBox}>
                    <View style={styles.demandContent}>
                        <View style={styles.demandRow}>
                            <Text
                                style={styles.demandTitle}>[{this.state.demand.asset_type || '-'}] {this.state.demand.asset_name}</Text>
                        </View>
                        <View style={[base.rowCC, styles.demandRow]}>
                            <Text allowFontScaling={false} style={styles.demandType}>{DemandState[this.state.demand.audit_state]}</Text>
                            <Text
                                style={styles.demandAmount}>{this.state.demand.capital_amount ? format.money(this.state.demand.capital_amount) + '万元' : ''}</Text>
                        </View>
                    </View>
                    <HorizontalMenu
                        textStyle={styles.menuText}
                        onPress={() => this.props.navigation.navigate('DemandDetail', {id: this.state.id})}
                        last={true}
                        style={styles.menu}
                        text="查看详情"/>
                </View>
                <ScrollView
                    ref="scrollView"
                    onContentSizeChange={() => this.toEnd()}
                    style={styles.container}>
                    {
                        this.state.list.map((item, index) => {
                            if (item.user_type === '01') {
                                return (
                                    <View key={index} style={[base.columnCC, styles.chatBoxLeft]}>
                                        <View style={styles.row}>
                                            <View style={[base.rowCC, styles.chatHeadBox]}>
                                                <Image
                                                    resizeMode={'contain'}
                                                    source={require('../../sources/icon_message_custom.png')}
                                                    style={styles.chatHeadLeft}/>
                                            </View>
                                            <Image source={require('../../sources/icon_message_point_left.png')}
                                                   style={styles.chatPoint}/>
                                            <View style={styles.chatContentLeft}>
                                                <Text allowFontScaling={false} style={styles.chatContent}>{item.message_content}</Text>
                                            </View>
                                        </View>
                                        <View style={styles.row}>
                                            <Text allowFontScaling={false} style={styles.chatDateLeft}>{item.create_date}</Text>
                                        </View>
                                    </View>
                                )
                            } else {
                                return (
                                    <View key={index} style={[base.columnCC, styles.chatBoxRight]}>
                                        <View style={styles.row}>
                                            <View style={styles.chatContentRight}>
                                                <Text allowFontScaling={false} style={styles.chatContent}>{item.message_content}</Text>
                                            </View>
                                            <Image source={require('../../sources/icon_message_point_right.png')}
                                                   style={styles.chatPoint}/>
                                            <View style={[base.rowCC, styles.chatHeadBox]}>
                                                <Image
                                                    resizeMode={'contain'}
                                                    source={require('../../sources/icon_mine_head.png')}
                                                    style={styles.chatHead}/>
                                            </View>
                                        </View>
                                        <View style={styles.row}>
                                            <Text allowFontScaling={false} style={styles.chatDateRight}>{item.create_date}</Text>
                                        </View>
                                    </View>
                                )
                            }
                        })
                    }
                </ScrollView>
                <Animated.View style={[base.rowCC, styles.chatInputBox, {
                    marginBottom: this.state.keyHeight
                }]}>
                    <View style={styles.chatInput}>
                        <TextInput
                            value={this.state.sendMessage}
                            maxLength={100}
                            onChangeText={(text) => this.inputChange(text)}
                            autoCorrect={false}
                            autoCapitalize="none"
                            underlineColorAndroid="transparent"
                            multiline={false}
                            style={styles.chatInputInner}
                            placeholder="请输入回复内容..."/>
                    </View>
                    <TouchableOpacity
                        onPress={() => this.state.sendMessage ? this.submit() : {}}
                        activeOpacity={layout.TOUCH_OPACITY_ACTIVE}>
                        <View style={[base.rowCC, styles.chatBtnBox, {
                            backgroundColor: this.state.sendMessage ? layout.MAIN_COLOR : layout.DISABLED_COLOR
                        }]}>
                            <Text allowFontScaling={false} style={styles.chatBtn}>发送</Text>
                        </View>
                    </TouchableOpacity>
                </Animated.View>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    demandBox: {
        backgroundColor: '#fff'
    },
    demandContent: {
        paddingVertical: layout.GAP_VERTICAL_MID,
    },
    demandRow: {
        paddingHorizontal: layout.GAP_HORIZONTAL_LARGE,
        paddingVertical: layout.GAP_VERTICAL_SMALL,
    },
    demandTitle: {
        color: layout.MAIN_AUX_COLOR,
        fontSize: layout.font(32)
    },
    demandType: {
        flex: 1,
        color: layout.MAIN_COLOR,
        fontSize: layout.font(28)
    },
    demandAmount: {
        color: layout.MAIN_COLOR,
        fontSize: layout.font(28)
    },
    menu: {
        borderTopColor: layout.MAIN_BORDER_COLOR_C1,
        borderTopWidth: layout.LINE_WIDTH,
        borderBottomColor: layout.MAIN_BORDER_COLOR_C1,
        borderBottomWidth: layout.LINE_WIDTH
    },
    menuText: {
        fontSize: layout.font(28),
        color: layout.MAIN_COLOR
    },
    container: {
        flex: 1
    },
    chatBoxLeft: {
        paddingRight: layout.width(100),
        paddingVertical: layout.GAP_VERTICAL_MID
    },
    chatBoxRight: {
        paddingLeft: layout.width(100),
        paddingVertical: layout.GAP_VERTICAL_MID
    },
    row: {
        flexDirection: 'row'
    },
    chatHeadBox: {
        marginHorizontal: layout.width(28),
        width: layout.width(80),
        height: layout.height(80),
        borderRadius: layout.width(8),
        backgroundColor: '#fff'
    },
    chatHeadLeft: {
        width: layout.width(64),
        height: layout.height(64)
    },
    chatHead: {
        width: layout.width(80),
        height: layout.height(80),
    },
    chatPoint: {
        marginTop: layout.height(30),
        width: layout.width(10),
        height: layout.height(20),
    },
    chatContentLeft: {
        flex: 1,
        padding: layout.width(24),
        borderRadius: layout.width(8),
        backgroundColor: '#fff'
    },
    chatContentRight: {
        flex: 1,
        padding: layout.width(24),
        borderRadius: layout.width(8),
        backgroundColor: '#fff'
    },
    chatContent: {
        color: layout.MAIN_AUX_COLOR,
        fontSize: layout.font(28),
        lineHeight: layout.heightToFixed(32)
    },
    chatDateLeft: {
        flex: 1,
        paddingTop: layout.GAP_VERTICAL_SMALL,
        color: layout.FORM_AUX_FONT_COLOR,
        fontSize: layout.font(20),
        textAlign: 'right'
    },
    chatDateRight: {
        flex: 1,
        paddingTop: layout.GAP_VERTICAL_SMALL,
        color: layout.FORM_AUX_FONT_COLOR,
        fontSize: layout.font(20)
    },
    chatInputBox: {
        padding: layout.GAP_VERTICAL_MID,
        backgroundColor: '#fff'
    },
    chatInput: {
        flex: 1,
        alignSelf: 'stretch',
        marginLeft: layout.GAP_HORIZONTAL_MID,
        borderBottomColor: layout.MAIN_BORDER_COLOR,
        borderBottomWidth: layout.LINE_WIDTH
    },
    chatInputInner: {
        flex: 1,
        alignSelf: 'stretch',
        fontSize: layout.font(24),
        includeFontPadding: false
    },
    chatBtnBox: {
        marginHorizontal: layout.GAP_HORIZONTAL_MID,
        width: layout.width(128),
        height: layout.height(60),
        borderRadius: layout.width(8),
        backgroundColor: layout.DISABLED_COLOR
    },
    chatBtn: {
        color: '#fff',
        fontSize: layout.font(28)
    }
})

//路由
const Message = {
    screen: Views,
    navigationOptions: {
        header: null,
    },
    name: 'Message',
    sign: true
};

export default Message;